package com.fingard.dsp.bank.directbank.gzdsf01;

import cfbs.api.CFBSMsgUtil;
import cfbs.model.CfbsPlMsg;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.directbank.gzdsf01.util.FtpUtil;
import com.fingard.dsp.bank.directbank.gzdsf01.util.JSONUtil;
import com.fingard.dsp.bank.helpers.SeqBatchInfo;
import com.fingard.dsp.bank.helpers.SeqBatchInfoHelper;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.SplitHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.ZipUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;

/**
 * 广州集中代收付系统对账单
 */
public class GZDSF01Statement extends GZDSF01Base implements IStatement {
    @Override
    public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
        RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
        retAts.writeStart();

        String[] unifiedRespHeader = getUnifiedStatementByFTP(p_reqQrySttm, retAts);
        String unifiedTotalNum = retAts.totalNum;

        if ("-1".equals(unifiedRespHeader[0])) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo("统一收单对账单获取失败,原因:" + unifiedRespHeader[1]);
        } else {
            if (retAts.getWrittenRdCount() == 0) {
                retAts.writeRespCode("0");

                String tmpRespInfo = "";
                if (StringHelper.isNullOrEmpty(tmpRespInfo)) {
                    tmpRespInfo = unifiedRespHeader[1];
                }
                if (StringHelper.isNullOrEmpty(tmpRespInfo)) {
                    tmpRespInfo = "交易为空";
                }
                retAts.writeRespInfo(tmpRespInfo);
            }
            retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(unifiedTotalNum)));
        }

        retAts.writeEnd();
        return retAts;
    }

    private String[] getUnifiedStatementByFTP(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) throws Exception {
        String[] tmpRespHeader = new String[]{"", ""};

        String tmpRespCode = "";
        String tmpRespInfo = "";

        retAts.totalNum = "0";
        int totalNum = 0;

        FTPClient ftpClient = null;

        try {
            FtpSet ftpSet = bankFront.getFtpSet("bat-down");
            ftpClient = FtpUtil.getConnectedClient(ftpSet.serverIP, ftpSet.port, ftpSet.userName, ftpSet.userPassword);
            boolean isChangePath = ftpClient.changeWorkingDirectory(ftpSet.downDir);
            if (isChangePath) {
                String ftpLocalDirRec = getBankConfig().getValueAsFilePath("ftpLocalDirRec");
                File mdDir = new File(ftpLocalDirRec);
                if (!mdDir.exists()) {
                    mdDir.mkdirs();
                }
                ftpLocalDirRec = StringHelper.trimEnd(ftpLocalDirRec, File.separator) + File.separator;

                FTPFile[] files = ftpClient.listFiles();
                if (files == null || (files != null && files.length == 0)) {
                    retAts.totalNum = String.valueOf(totalNum);
                    tmpRespHeader[0] = "0";
                    tmpRespHeader[1] = "ftp服务器暂无结果文件";
                    return tmpRespHeader;
                }

                for (FTPFile file : files) {
                    boolean isDownload = FtpUtil.download(ftpClient, file.getName(), ftpLocalDirRec + file.getName());
                    if (isDownload) {
                        WriteBankLogLn("回应解密前文件名：" + file.getName());
                        //将密文文件解密解压，decFileName为可读的明文文件名
                        CFBSMsgUtil.KEY = getEncryptKey();
                        String decFileName = "";
                        try {
                            decFileName = CFBSMsgUtil.fileDec(ftpLocalDirRec, file.getName());
                        } catch(Exception ex) {
                            WriteBankLogLn("回应文件名解密失败,当前文件无效，继续解密其他文件.");
                            continue;
                        }

                        WriteBankLogLn("回应解密后文件名：" + decFileName);
                        if (StringHelper.isNullOrEmpty(decFileName) || !decFileName.startsWith("DTLTYP")) {
                            WriteBankLogLn("解密" + ftpLocalDirRec + file.getName() + "后文件名为空或者非对账单文件");
                            continue;
                        }

                        if (p_reqQrySttm.busDate.equalsIgnoreCase(decFileName.substring(25, 33))) {
                            //按照交易类型分类，将明文文件解析成对象
                            String tmpStrRet = FileHelper.readFileText(ftpLocalDirRec + decFileName, getCharset());
                            WriteBankLogLn("对账单响应结果数据：" + tmpStrRet);

                            if (StringHelper.hasAnyChar(tmpStrRet)) {
                                tmpRespCode = "0";

                                StringReader strReader = new StringReader(tmpStrRet);
                                BufferedReader tmpReader = new BufferedReader(strReader);

                                String titleLine = tmpReader.readLine();
                                String busType = titleLine.substring(8, 14);

                                while (true) {
                                    String dataLine = tmpReader.readLine();
                                    if (dataLine == null) {
                                        break;
                                    }
                                    totalNum++;

                                    RetAtsStatementDetail retDetail = new RetAtsStatementDetail();
                                    retDetail.busTime = dataLine.substring(16, 24) + "000000";
                                    retDetail.askNumber = dataLine.substring(0, 16);
                                    if (GZDSF01TransCode.REALTIMEPAY.equalsIgnoreCase(busType)) {
                                        retDetail.cdFlag = "27";
                                        retDetail.amount = Format.DecimalAmtFormat.format(Double.parseDouble(new String(dataLine.getBytes(getCharset()), 259, 15)));
                                    } else {
                                        retDetail.cdFlag = "22";
                                        retDetail.amount = Format.DecimalAmtFormat.format(Double.parseDouble(new String(dataLine.getBytes(getCharset()), 258, 15)));
                                    }
                                    retDetail.oppAct = new String(dataLine.getBytes(getCharset()), 98, 35, getCharset()).trim();
                                    retDetail.oppActName = new String(dataLine.getBytes(getCharset()), 133, 60, getCharset()).trim();
                                    retDetail.transState = TransState.Success;

                                    retAts.writeRetDetail(retDetail);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.totalNum = String.valueOf(totalNum);

        tmpRespHeader[0] = tmpRespCode;
        tmpRespHeader[1] = tmpRespInfo;

        return tmpRespHeader;
    }
}